function [ChEstimate_OUT,error] = HF_LSChEst(ChOutput, ChInput, ChLength, Oversample)
% ***************************************************
%
% INPUTS:
%        ChOutput : The outputs of the channel sampled at one sample per symbol
%        ChInput  : The input symbols to the channel sampled at one sample per symbol
%        ChLength : Length of composite channel
%
% OUTPUTS:
%       ChEstimate: estimated composite channel, i.e. (KnownCh*UnKnownCh)
%       error2    : square sum of the estimation error.
% ********************************************************

ChEstimate_OUT = zeros(1,ChLength);
ChOutput_iter = ChOutput;
ChOutput_test = ChOutput(6*Oversample+1:end);
ChInput_test = ChInput(6*Oversample+1:end);

ChLength_DownSampled = ceil(ChLength/Oversample);

for Iter = 1:2
    
    ChEstimate_OUT = zeros(1,ChLength);
    
    for path_no = 1:3
        
        for phase = 1:Oversample
            Ch_IN(phase,:) = ChInput_test(1:Oversample:end);
            Ch_OUT(phase,:) = ChOutput_test(phase:Oversample:end);
            
            for index = 1:ChLength_DownSampled
                H(:,index) = Ch_IN(phase,ChLength_DownSampled-index+1:end-index+1).';
            end
            
            ChEstimate(phase,:) = pinv(H'*H)*H'*Ch_OUT(phase,ChLength_DownSampled:end).';
        end
        
        Path_values = (reshape(ChEstimate,1,[]));
        [Path_abs path_index(path_no)] = max(abs(Path_values));
        Path(path_no) = Path_values(path_index(path_no));
        if (ChEstimate_OUT(path_index(path_no)) == 0)
            ChEstimate_OUT(path_index(path_no)) = Path(path_no);
        end
        
        Path_Effect = Path(path_no)*ChInput;
        ChOutput = ChOutput - [zeros(1,path_index(path_no)-1) Path_Effect(1:end-path_index(path_no)+1)];
        
        ChOutput_test = ChOutput(6*Oversample+1:end);
        
    end
    
    Path_Effect = Path(2)*ChInput;
    ChOutput = ChOutput_iter - [zeros(1,path_index(2)-1) Path_Effect(1:end-path_index(2)+1)];
    ChOutput_test = ChOutput(6*Oversample+1:end);
    ChOutput = ChOutput_iter;
    
end

ChOutput_fromestimation = conv(ChInput,ChEstimate_OUT);

ChOutput_fromestimation = ChOutput_fromestimation(1:length(ChOutput));

error_vector = ChOutput_fromestimation - ChOutput;

error = mean (abs(error_vector).^2);

end

